package com.hankkin.reading.control

import com.zhsm.paipaiout.baselibrary.http.cookies.CookiesManager
import com.zhsm.paipaiout.baselibrary.utils.LogUtils
import com.zhsm.paipaiout.baselibrary.utils.SPUtils
import com.zhsm.fuxi.bean.UserBean

object UserControl {
    const val USER = "user"

    private var user: UserBean? = null

    init {

    }

    fun setCurrentUser(userBean: UserBean) {
        this.user = userBean
        saveUserSp(userBean)
    }

    fun getCurrentUser(): UserBean? {
        if (this.user == null) {
            this.user = SPUtils.getObject(USER, UserBean::class.java) as UserBean
        }
        return this.user
    }


    fun changeEmail(email: String) {
        if (this.user == null) {
            this.user = SPUtils.getObject(USER, UserBean::class.java) as UserBean
        }
        user?.let {
            it.email = email
            saveUserSp(it)
        }
    }

    fun changeNick(nick: String) {
        if (this.user == null) {
            this.user = SPUtils.getObject(USER, UserBean::class.java) as UserBean
        }
        user?.let {
            it.nick = nick
            saveUserSp(it)
        }
    }

    private fun saveUserSp(userBean: UserBean) {
        SPUtils.saveObject(USER, userBean)
        LogUtils.d(USER + userBean.id)
    }

    fun isLogin(): Boolean {
        val user = SPUtils.getObject(USER, UserBean::class.java)
        if (user != null) return true
        return false
    }

    fun logout() {
        this.user = null
        SPUtils.clear()
        CookiesManager.clearAllCookies()
    }

    fun getId(): Long {
        if (this.user == null) {
            this.user = SPUtils.getObject(USER, UserBean::class.java) as UserBean
        }
        return if (user?.id != null) {
            user?.id!!
        } else -1
    }
}
